import config from '@/config.js'
import {
	pcLogin,
	getNowOpenId,
	initData
} from './login'

const excludeUrls = ['/system/wx/getUserInfo']

// 获取Token
function getToken() {
	try {
		const token = uni.getStorageSync('token');
		if (token) {
			return token
		} else {
			return ''
		}
	} catch (e) {
		console.log(e)
	}
}

// 获取请求头
function getHeaders() {
	let token = getToken()
	let header = {
		"Authorization": token,
		"Content-Type": "application/json", //根据自己的数据类型
		// "Content-Type":"application/x-www-form-urlencoded",
	}
	return header
}

let request = function(req) {
	req.method = req.method.toUpperCase()
	if (!['GET', 'POST','PUT', 'DELETE'].includes(req.method)) {
		uni.showToast({
			title: `暂不支持的请求方式: ${req.method}`,
			icon: 'none'
		});
		return
	}

	// if (req.method == 'POST' && !req.hideLoding) {
	// 	uni.showLoading({
	// 		title: '提交中...'
	// 	})
	// }

	return new Promise((resolve, reject) => {
		uni.request({
			url: config.baseUrl_api + req.url,
			method: req.method,
			data: req.params,
			header: getHeaders(),
		}).then(res => {
			switch (res.statusCode) {
				case 200:
					const data = res.data || {};
					if (data.code == 200) {
						resolve(data)
					} else {
						//登录超时
						if (data.code == 60002 || data.code == 60001) {
							if (req.url != '/system/wx/getUserInfo') {
								reLogin();
							}
						} 
						else if (data.code == 401 && req.url != '/system/wx/getUserInfo') {
							pcLogin()
							.then(()=>{
								return getNowOpenId()
							})
							.then(()=>{
								return initData()
							})
							.then(()=>{
								uni.hideLoading();
								uni.redirectTo({
									url:getCurrentPages()[getCurrentPages().length-1].$page.fullPath
								})
							})
						}
						 else {
							if (!excludeUrls.includes(req.url)) {
								uni.showToast({
									title: data.msg,
									icon: 'none',
									duration: 3000
								})
							}
						}
						reject(res)
					}
					break
				default:
					reject(res)
			}
		}).catch(res => {
			reject(res)
		}).finally(() => {
			// if (req.method == 'POST' && !req.hideLoding) {
			// 	uni.hideLoading()
			// }
		})
	})
}

function reLogin() {
	const currUser = uni.getStorageSync('currUser') || {}
	if (currUser.openId) {
		const accountInfo = uni.getAccountInfoSync()
		pcLoginByOpenId(accountInfo.miniProgram.appId, currUser.openId)
			.then((res) => {
				let user = res.data;
				uni.setStorageSync('token', 'Bearer ' + user.token);
				uni.setStorageSync('currUser', user);

				uni.showToast({
					title: '一走神把您的操作遗漏了，请重试',
					icon: 'none'
				})
			}).catch(() => {
				uni.showToast({
					title: '服务异常，请稍后重试',
					icon: 'none'
				})
			})
	}
}

function pcLoginByOpenId(appId, openId) {
	return request({
		url: "/system/wx/loginByOpenId",
		method: "POST",
		params: {
			appId: appId,
			openId: openId
		}
	})
}


export default request;
